/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.kariqu.cldld.wss;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;

/**
 * Echoes uppercase content of text frames.
 */
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class);

    public WebSocketFrameHandler() {
    }

    //通道创建监听
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelActive channel_id: {}", ctx.channel().id().asShortText());
    }

    //通道销毁监听
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelInactive channel_id: {}", ctx.channel().id().asShortText());
    }

    //监听通道事件
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case READER_IDLE:          //读取超时
                    handleReaderIdle(ctx);
                    break;
                case WRITER_IDLE:         //写入超时
                    handleWriterIdle(ctx);
                    break;
                case ALL_IDLE:              //全部超时
                    handleAllIdle(ctx);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 消息读取
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        decoder(ctx, frame);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.warn("exception: {}", cause.toString());
        closeChannle(ctx);
    }

    private void decoder(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            String request_encrypt = ((TextWebSocketFrame) frame).text();

            if(request_encrypt.isEmpty() || request_encrypt.trim().isEmpty())
                return;

            String request = "";
            // 解密
            try {
                //request = Utility.decrypt(request_encrypt);
                request = request_encrypt;
                System.out.println("收到消息-----------》" + request);
            } catch (Exception e) {
                Channel channel = ctx.channel();
                String str = String.format("decode websocket request decrypt error. shutdownChannel channel: %s %s"
                        , e.toString(), channel.id().asShortText());
                throw new UnsupportedOperationException(str);
            }


        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }


    private void handleReaderIdle(ChannelHandlerContext ctx) {
        logger.info("reader idle. {}", ctx.channel().id().asShortText());
        closeChannle(ctx);
    }

    private void handleWriterIdle(ChannelHandlerContext ctx) {
        logger.info("writer idle. {}", ctx.channel().id().asShortText());
        closeChannle(ctx);
    }

    private void handleAllIdle(ChannelHandlerContext ctx) {
        logger.info("all idle. {}", ctx.channel().id().asShortText());
        closeChannle(ctx);
    }

    private void closeChannle(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        channel.writeAndFlush(CloseFramer.normalClose());
        ChannelFuture f2 = ctx.close();
    }
}
